how to index a username in mongo with case 您所在的位置:网站首页 mongo collation how to index a username in mongo with case

how to index a username in mongo with case

2023-03-22 06:17| 来源: 网络整理| 查看: 265

Answer a question

I am coding a webservice where users can pick a username that has to be case-insensitive unique. However I want to allow them to use a case-sensitive version of their username.

What is the best way to check at insert that the username doesn't have a case-insensitive duplicate? I currently see 2 ways of doing this:

storing both a lowercase version and another version with the case entered by the user, and indexing only the lowercase version store only the version with the case entered by the user and lowercase it for comparison, which defeats the purpose of the index I suppose

Is there a better way?

Answers

MongoDB 3.4 now includes the ability to make a true case-insensitive index. It is made by specifying a collation with a strength of 2.

Probably the easiest way to do it is to set a collation on the database itself. Then all queries inherit that collation and will use it:

db.createCollection("cities", { collation: { locale: 'en_US', strength: 2 } } ) db.cities.createIndex( { city: 1 } ) // inherits the default collation db.cities.find({city:"new york"}) //inherits default collation

Or you can do it on an index by index basis:

db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}});

And use it like this:

db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2});

For more info: https://jira.mongodb.org/browse/SERVER-90



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有